<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Enkuso
 * Date: 11/19/12
 * Time: 1:51 PM
 * To change this template use File | Settings | File Templates.
 */
class bookstoreFilter extends sfFilter
{
    public function execute($filterChain)
    {
        $request = $this->getContext()->getRequest();
        $format = $request->getParameter('sf_format');
        $valid = true;

        /**
         * API Key шалгах
         */
        if(!$this->isValidApiKey($request->getParameter('api_key',false))){
            $valid = false;
            $response = $this->getContext()->getResponse();
            $response->setStatusCode(200);
            if($format == 'json'){
                $response->setHttpHeader('Content-Type', 'application/json; charset=utf-8', true);
                $response->setContent(json_encode(array('stat'=>'fail','code' => '100', 'message' => apiErrors::getErrorMessage(100))));
            } elseif($format == 'xml'){
                $response->setHttpHeader('Content-Type', 'text/xml', true);
                $response->setContent('<?xml version="1.0" encoding="utf-8" ?><rsp stat="fail"><err code="100" msg="'.apiErrors::getErrorMessage(100).'"/></rsp>');
            } else{
                $response->setStatusCode(404);
            }
        }

        /**
         * User Token шалгах
         */
        if($request->hasParameter('token') && !$this->isValidUserToken($request->getParameter('token'))){
            $valid = false;
            $response = $this->getContext()->getResponse();
            $response->setStatusCode(200);
            if($format == 'json'){
                $response->setHttpHeader('Content-Type', 'application/json; charset=utf-8', true);
                $response->setContent(json_encode(array('stat'=>'fail','code' => '98', 'message' => apiErrors::getErrorMessage(98))));
            } elseif($format == 'xml'){
                $response->setHttpHeader('Content-Type', 'text/xml', true);
                $response->setContent('<?xml version="1.0" encoding="utf-8" ?><rsp stat="fail"><err code="98" msg="'.apiErrors::getErrorMessage(98).'"/></rsp>');
            } else{
                $response->setStatusCode(404);
            }
        }

        $user = $this->getContext()->getUser();

        /**
         * Номны дэлгэрэнгүй мэдээлэл авах үед
         * - номын хамгийн сүүлд сонирхсон огноог хадгалах
         * - номын нийт үзсэн тоог нэмэгдүүлэх
         * - бүртгэлтэй хэрэглэгч бол History жагсаалтад нэмэх
         */
        if($this->getContext()->getModuleName() == 'book' && $this->getContext()->getActionName() == 'info'){

            $book_id = $request->getParameter('id');

            $update = Doctrine_Query::create()
                ->update('Book b')
                ->set('b.view_count','b.view_count + 1')
                ->set('b.last_viewed_at','?',date('Y-m-d H:i:s'))
                ->where('b.id = ?', $book_id)
                ->execute();

            if($user->isAuthenticated() && $update){
                $view_history = new ViewHistory();
                $view_history->setBookId($book_id);
                $view_history->setUser($user->getGuardUser());
                $view_history->replace();
            }
        }

        // execute next filter
        if($valid)
            $filterChain->execute();
    }

    /**
     * API Key шалгах
     */
    public function isValidApiKey($api_key)
    {
         return in_array($api_key, sfConfig::get('app_api_keys'));
    }

    /**
     * User Token шалгах
     *
     * @param $token
     */
    public function isValidUserToken($token)
    {
        $q = Doctrine_Core::getTable('UserToken')->createQuery('r')
            ->innerJoin('r.User u')
            ->where('r.token = ?', $token);

        if ($q->count()) {
            $this->context->getUser()->signIn($q->fetchOne()->User);
            return true;
        }

        return false;
    }
}
